#include "Compilation.hpp"
#include "Binding/Binder.hpp"
#include "Evaluator.hpp"
#include <mutex>
#include  <iostream>
#include <stdio.h>
std::shared_mutex Compilation::sharedMutex;

SharedBoundGlobalScope Compilation::GlobalScope()
{
    if (this->_globalScope == nullptr)
    {
        SharedBoundGlobalScope previous = Previous == nullptr ? nullptr : Previous->GlobalScope();

        auto globalScope                = Binder::BindGlobalScope(previous, this->mSyntaxTree->Root);
        // 加锁;
        std::unique_lock<std::shared_mutex> lock(sharedMutex);
        this->_globalScope = globalScope;
    }
    return this->_globalScope;
}

EvaluationResult Compilation::Evaluate(SharedVariableMap variable)
{
    // 诊断信息;
    SharedDiagnosticBag diagnostics = mSyntaxTree->Diagnostics;

    if (diagnostics->Diagnostics().empty())
    {
        if (GlobalScope()->Diagnostics->Diagnostics().empty())
        {
            // 不存在诊断信息;
            // 开始计算;
            SharedBoundBlockStatement statement = this->GetStatement();
            Evaluator                 evaluator = Evaluator(statement, variable);
            SharedObject              value     = evaluator.Evaluate();

            return EvaluationResult(nullptr, value);
        }

        // 合并诊断信息;
        diagnostics->AddRange(GlobalScope()->Diagnostics);
    }
    return EvaluationResult(diagnostics, nullptr);
}